package com.example.demo.util;

import org.springframework.util.Assert;
import org.springframework.util.StreamUtils;

import javax.validation.constraints.NotNull;
import java.io.*;

public class CommandUtils {

    /**
     * @param command
     * @throws InterruptedException 当执行命令的线程被打断时会抛出此异常
     * @throws IOException          命令不正确时会抛出此异常
     */
    public static String exec(@NotNull String command) throws IOException, InterruptedException {
        return exec(command, null);
    }


    public static String exec(@NotNull String command, File dir) throws IOException, InterruptedException {
        Process exec = null;
        try {
            exec = Runtime.getRuntime().exec(command, null, dir);
            int                   exitValue = exec.waitFor();// 等待该命令执行完毕
            ByteArrayOutputStream out       = new ByteArrayOutputStream();
            if (exitValue == 0) {
                copy(exec.getInputStream(), out);
            } else {
                copy(exec.getErrorStream(), out);
            }
            return new String(out.toByteArray());
        } finally {
            if (exec != null) {
                exec.destroy();
            }
        }
    }

    private static OutputStream copy(InputStream in, OutputStream out) throws IOException {
        int    byteCount = 0;
        byte[] buffer    = new byte[1024];
        int    bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return out;
    }
}
